 <template>
  <div class="container">
    <div class="main">
      <div class="main_content">
        <div class="main_header">
          <a-steps :current="currentIndex">
            <a-step>
              <!-- <span slot="title">Finished</span> -->
              <template slot="title"> 活动配置 </template>
              <span slot="description">作为筹划活动的必要部分</span>
            </a-step>
            <a-step title="操作完成" description="活动配置完成" />
          </a-steps>
        </div>
        <div class="main_table">
          <!-- data-source 数据源,column 列名  row-selection列表项是否可选择	-->
          <!-- rowSelection 是计算属性进行加工处理 -->
          <a-form-model
            ref="ruleForm"
            :model="form"
            :rules="rules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-tabs
              :activeKey="activeKey"
              default-active-key="1"
              :tab-position="mode"
              :style="{ height: '800px' }"
              @change="change"
            >
              <a-tab-pane tab="活动筹划" key="1">
                <!-- 试卷名称  -->
                <a-form-model-item ref="test" label="活动名称" prop="test">
                  <a-input
                    v-model="form.test"
                    @blur="
                      () => {
                        $refs.test.onFieldBlur();
                      }
                    "
                  />
                </a-form-model-item>

                <a-form-model-item ref="desc" label="活动描述" prop="desc">
                  <a-input
                    v-model="form.desc"
                    @blur="
                      () => {
                        $refs.desc.onFieldBlur();
                      }
                    "
                  />
                </a-form-model-item>
                <a-form-model-item
                  ref="address"
                  label="活动地点"
                  prop="address"
                >
                  <a-input
                    v-model="form.address"
                    @blur="
                      () => {
                        $refs.address.onFieldBlur();
                      }
                    "
                  />
                </a-form-model-item>
                <a-form-model
                  ref="ruleForm2"
                  :rules="rules"
                  :label-col="labelCol"
                  :wrapper-col="wrapperCol"
                >
                  <a-form-item label="签到时间" style="margin-top: 20px">
                    <div>
                      <a-date-picker
                        show-time
                        placeholder="请确认签到时间"
                        @change="onDataChange"
                        @ok="confirm"
                        v-model="sign_time"
                      />
                    </div>
                  </a-form-item>
                </a-form-model>
                <a-form-model
                  ref="ruleForm2"
                  :rules="rules"
                  :label-col="labelCol"
                  :wrapper-col="wrapperCol"
                >
                  <a-form-item
                    label="开始/结束日期"
                    style="margin-bottom: 0; margin-top: 20px"
                    v-if="showClassVisible == false"
                  >
                    <div>
                      <a-range-picker
                        @change="getDateTime"
                        showToday
                        :default-value="[
                          moment(getCurrentDataL(), dateFormat),
                          moment(getCurrentDataR(), dateFormat),
                        ]"
                        :format="dateFormat"
                      >
                        <template slot="dateRender" slot-scope="current">
                          <div
                            class="ant-calendar-date"
                            :style="getCurrentStyle(current)"
                          >
                            {{ current.date() }}
                          </div>
                        </template>
                      </a-range-picker>
                    </div>
                  </a-form-item>
                  <a-form-item
                    label="开始/结束日期"
                    style="margin-bottom: 0"
                    v-else
                  >
                    <div>
                      <a-range-picker @change="getDateTime">
                        <template slot="dateRender" slot-scope="current">
                          <div
                            class="ant-calendar-date"
                            :style="getCurrentStyle(current)"
                          >
                            {{ current.date() }}
                          </div>
                        </template>
                      </a-range-picker>
                    </div>
                  </a-form-item>

                  <a-form-item
                    label="开始/结束时间"
                    style="margin-bottom: 0; margin-top: 20px"
                  >
                    <a-time-picker
                      v-model="handleTime.startTime"
                      format="HH:mm:ss"
                      @change="getStartTime"
                      :open="open"
                      @openChange="handleOpenChange"
                      style="margin-right: 10px"
                    >
                    </a-time-picker>
                    -
                    <a-time-picker
                      :open.sync="open2"
                      style="margin-left: 10px"
                      @change="getEndTime"
                      v-model="handleTime.endTime"
                    >
                    </a-time-picker>
                  </a-form-item>
                </a-form-model>

                <a-form-model-item
                  :wrapper-col="{ span: 14, offset: 7 }"
                  style="margin-top: 50px"
                >
                  <a-button type="primary" @click="addOrUpdateActive">
                    {{ desWord }}
                  </a-button>
                  <a-button style="margin-left: 10px" @click="resetForm">
                    重置
                  </a-button>
                </a-form-model-item>
              </a-tab-pane>
            </a-tabs>
          </a-form-model>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import moment from "moment";
export default {
  data() {
    return {
      is_modify: false,
      sign_time: "",
      dateFormat: "YYYY-MM-DD",
      // 控制班级框的显示与隐藏
      showClassVisible: true,
      // Tab2 中选中的id 和所有数据
      idList: [],
      selectForm: [],
      // 时间模块
      open: false,
      open2: false,
      // 默认配置信息
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      form: {
        address: "",
        //   该试卷的描述信息
        desc: "",
        class_id: "",
        class: [],
        // 试卷名称
        test: "",
        sign_time: "",
        startTime: "",
        endTime: "",
        // 分配的学生信息
        studentId: [],
      },
      rules: {
        address: [
          {
            required: true,
            message: "请填写活动的地点",
            trigger: "blur",
          },
        ],
        desc: [
          {
            required: true,
            message: "请填写活动的描述信息",
            trigger: "blur",
          },
        ],
        test: [
          {
            required: true,
            message: "请填写活动的名称",
            trigger: "blur",
          },
        ],
      },
      // 是否能够进入下一页
      allowToNextTab: false,
      // 当前进度条的索引
      currentIndex: 0,
      //Tab Key
      activeKey: "1",
      mode: "left",
      // 搜索框内容
      record: {},
      handleTime: {
        // 用户选择的开始时间 --(时分秒)
        startTime: "",
        endTime: "",
        // 稍加转换的时分秒
        startTimeToChange: "",
        endTimeToChange: "",
        // 日期
        startTimeYear: "",
        endTimeYear: "",
      },
      // 班级列表 查出的学生id
      classStudentList: "",
    };
  },
  created() {
    this.init();
  },
  methods: {
    // 接收 Tab2  emit 方法用于接收班级id 来拿到学生信息
    async getFocusClassInTable(classList) {
      console.log("classList", classList);
      // 拿到班级列表之后 发送请求 拿到学生列表
      const { data: res } = await this.$http.get(
        `/admin/teacher/student/class`,
        {
          params: {
            classIds: classList,
          },
          paramsSerializer: function (params) {
            return params.classIds.map((_) => `classIds=${_}`).join("&");
          },
        }
      );
      console.log("studentIds", res.data);
      this.classStudentList = res.data;
    },

    // onChange
    onDataChange(value, dateString) {
      console.log("Formatted Selected Time: ", dateString);
      let formatDate = new Date(dateString);
      this.form.sign_time = formatDate.getTime();
      console.log("sign_time: ", this.form.sign_time);
    },
    confirm(value) {
      // moments
      console.log("confirm: ", value);
    },
    // 完成分配 组卷完成
    async addOrUpdateActive() {
      if (!this.record) {
        // 新增操作
        this.form.studentId = [...this.classStudentList];
        // 去重 班级的学生 和 选择的学生
        this.form.studentId = this.unique(this.form.studentId);
        const { data: res } = await this.$http.post("/admin/activity", {
          students: this.form.studentId,
          title: this.form.test,
          desc: this.form.desc,
          address: this.form.address,
          signTime: this.form.sign_time,
          startTime: this.form.startTime,
          endTime: this.form.endTime,
        });
        if (res.code == 200) {
          this.common.notify("success", "新增成功");
          this.$router.push({
            name: "active",
          });
        } else {
          this.common.notify("error", "新增失败");
        }
      } else {
        //修改操作
        let formatDate = new Date(this.sign_time);
        // console.log("now", this.sign_time);
        this.form.sign_time = formatDate.getTime();
        // console.log("startTime", this.form.startTime);
        // console.log("endTime", this.form.endTime);
        const { data: res } = await this.$http.put("/admin/activity", {
          id: this.record.id,
          title: this.form.test,
          desc: this.form.desc,
          address: this.form.address,
          signTime: this.form.sign_time,
          startTime: this.form.startTime,
          endTime: this.form.endTime,
        });

        if (res.code == 200) {
          this.common.notify("success", "修改成功");
          this.$router.push({
            name: "active",
          });
        } else {
          this.common.notify("error", "修改失败");
        }
      }
    },
    //  emit 方法用于接收参加活动学生的参数
    getStudentDate(studentIdList) {
      this.form.studentId = studentIdList;
    },
    moment,
    startTime() {
      if (this.showClassVisible == true) {
        return null;
      } else {
        let arr = this.record.startTime.split(" ");
        this.handleTime.startTime = arr[1]; //设置默认值 为之前新增时确定的
        return arr[1];
      }
    },
    endTime() {
      if (this.showClassVisible == true) {
        return null;
      } else {
        let arr = this.record.endTime.split(" ");
        this.handleTime.endTime = arr[1]; //设置默认值 为之前新增时确定的
        return arr[1];
      }
    },
    // 日期部分左边设定初值
    getCurrentDataL() {
      if (this.showClassVisible == true || this.record.endTime == null) {
        return null;
      } else {
        let arr = this.record.startTime.split(" ");
        this.handleTime.startTimeYear = arr[0];
        return arr[0];
      }
    },
    // 日期部分右边设置初始值
    getCurrentDataR() {
      if (this.showClassVisible == true || this.record.endTime == null) {
        return null;
      } else {
        let arr = this.record.endTime.split(" ");
        this.handleTime.endTimeYear = arr[0];
        return arr[0];
      }
    },

    // 对于时间的加工处理
    // 将开始时间转化为毫秒数
    getStartTime(value) {
      // 提取空间中 我们想要的 时间类型
      // TODO:  v-module 失效, this.handleTime.startTime 是一个值
      let d = new Date(this.handleTime.startTime);
      let date = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
      // 转化为时间戳
      let formatDate = new Date(this.handleTime.startTimeYear + " " + date);
      this.form.startTime = formatDate.getTime();
      console.log("131111", this.form.startTime);
    },
    // 将结束时间转化为毫秒数
    getEndTime(value) {
      let d = new Date(this.handleTime.endTime);
      let date = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
      // 转化为时间戳
      let formatDate = new Date(this.handleTime.endTimeYear + " " + date);
      this.form.endTime = formatDate.getTime();
      console.log(this.form.endTime);
    },
    getDateTime(data) {
      if (data) {
        this.handleTime.startTimeYear = data[0].format("YYYY-MM-DD");
        this.handleTime.endTimeYear = data[1].format("YYYY-MM-DD");
        console.log("Start-time", this.handleTime.startTimeYear);
        console.log("Start-time", this.handleTime.endTimeYear);
        this.getStartTime();
        this.getEndTime();
      }
      if (this.form.startTime) {
        // 如果已经存在 说明是时间的设定不对 修改日期的时候 重新获取毫秒数
      }
    },
    // 日期部分 样式的初始化
    getCurrentStyle(current, today) {
      const style = {};
      if (current.date() === 1) {
        style.border = "1px solid #1890ff";
        style.borderRadius = "50%";
      }

      return style;
    },
    // 时间部分 初始化
    handleOpenChange(open) {
      this.open = open;
    },
    // 时间部分的初始化
    handleClose() {
      this.open = false;
      this.open2 = false;
    },

    async init() {
      // 获取下拉框中的 题库分类选项
      let { record } = this.$route.params;
      // 若 record 则是更新操作
      this.record = record;
      if (record) {
        this.is_modify = true;
        this.showClassVisible = false;
        const { data: res } = await this.$http.get(
          `/admin/activity/${record.id}`
        );
        //  解构赋值 分离出 res.data 给data变量
        let { data } = res;
        console.log("data", data);
        this.record = data;
        this.form.address = data.address;
        this.form.desc = data.desc;
        this.form.test = data.title;
        this.form.class_id = data.id;
        // 如果有值 就进行... 如果没有值 => 永久试卷 => null
        let arr = this.record.startTime.split(" ");
        let handledata = arr[1];
        this.handleTime.startTime = moment(handledata, "HH:mm:ss");

        let arr2 = this.record.endTime.split(" ");
        handledata = arr2[1];
        this.handleTime.endTime = moment(handledata, "HH:mm:ss");
        this.sign_time = data.signTime;
        this.getStartTime();
        this.getEndTime();
      } else {
        this.is_modify = false;

        this.showClassVisible = true;
      }
    },

    // 完成按钮
    async finishExam() {
      this.change("3");
    },
    // 从第一个 Tab  跳转到 第二个Tab
    onSubmit() {
      // 修改的话 就提交
      if (this.is_modify) {
        this.addOrUpdateActive();
      } else {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.allowToNextTab = true; //允许到下一页
            this.change("2");
          } else {
            this.openNotificationWithIcon("info");
            return false;
          }
        });
      }
    },
    resetForm() {
      // 清空两个表单
      this.$refs.ruleForm.resetFields();
      this.$refs.ruleForm2.resetFields();
    },
    //   tab栏回调
    change(val) {
      // 不点击 下一页 直接点击 跳转
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.allowToNextTab = true;
        }
      });
      if (this.activeKey < val && this.activeKey == val - 1) {
        // 如果是依次跳转 就判断校验
        //往后跳转要进行验证
        if (this.allowToNextTab) {
          //如果填写项 通过的了验证 就跳转
          // 返回下一个列表 索引对应
          this.currentIndex = Number(val) - 1;
          this.activeKey = val; //active 控制跳转 若表单不完整 不显示跳转
          this.allowToNextTab = false; //重置
        } else {
          //   如果参数没填写全 就想着跳转
          this.openNotificationWithIcon("info");
        }
      } else if (this.activeKey < val && this.activeKey != val - 1) {
        this.common.notify("warning", "请依次确认信息");
      } else {
        //如果往前跳 就不考虑
        if (this.allowToNextTab) {
          //如果填写项 通过的了验证 就跳转
          // 返回下一个列表 索引对应
          this.currentIndex = Number(val) - 1;
          this.activeKey = val; //active 控制跳转 若表单不完整 不显示跳转
          this.allowToNextTab = false; //重置
        }
      }
    },
    // 消息提醒模态
    openNotificationWithIcon(type) {
      if (type == "info") {
        this.$notification[type]({
          message: "存在未知错误",
          description: "可能是由于填写信息没有通过校验所导致,请重新核查",
        });
      } else if (type == "success") {
        this.$notification[type]({
          message: "操作成功",
        });
      }
    },
    unique(arr) {
      return Array.from(new Set(arr));
    },
  },
  computed: {
    desWord() {
      return "完成";
    },
    changeKey() {
      // 如果是新增的话 key 为3
      if (this.is_modify == false) {
        return "3";
      } else {
        return "2";
      }
    },
  },
};
</script>
<style  lang='less' scoped>
.container {
  box-sizing: border-box;
  display: flex;
  background-color: #eef1f2;
  padding: 35px 75px;
  .main {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-items: center;
    background-color: #eef1f2;
    // box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    .main_content {
      padding: 20px;
      padding-top: 20px;
      width: 100%;
      height: 100%;
      background-color: #fff;
      border-radius: 10px;
      .main_header {
        display: flex;
        margin-bottom: 25px;
        .main_table {
          margin-top: 50px;
        }
      }
    }
  }
}
/deep/ .ant-table-thead > tr > th,
.ant-table-tbody > tr > td {
  text-align: center;
}
/deep/ .ant-table-tbody > tr > td {
  // 1516
  text-align: center !important;
}
.disableColor {
  color: #eee;
}
li {
  list-style: none;
  margin-top: 10px;
}
.btn_finish {
  margin-top: 60px;
  margin-left: 480px;
}
.btn_finish_Tab2 {
  margin-top: 220px;
  margin-left: 480px;
}
.table {
  width: 100%;
  height: 500px;
}
.finshScoreTable {
  width: 100%;
  height: 500px;
}
// timepicker 文字居中
/deep/ .ant-time-picker-panel-inner {
  text-align: center !important;
}
/deep/ .ant-time-picker-panel-addon {
  text-align: center !important;
}
</style>